﻿/********************************************************
 // Module Name    : Desktop ShortCuts
 // Purpose        : Show Setting Dialog
 // Class Used     : Envs.cs,Msg.cs
 // Created By     : Harwinder 
 // Date           : --------------------
**********************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Apps;
using VAdvantage.Utility;
using System.Reflection;
using VAdvantage.Logging;
using SilverlightDesktop.Controls;
using System.Data;

namespace VAdvantage.MainScreen
{
    public partial class SettingDialog : ChildWindow, IHost
    {
        /// <summary>
        /// List conating Image source for shortcutItems
        /// </summary>
        List<ImageSource> lstImgSource = new List<ImageSource>();

        /// <summary>
        /// Std Const
        /// </summary>
        public SettingDialog()
        {
            InitializeComponent();
            txtHeader.Text = Msg.GetMsg("Settings");
        }

        /// <summary>
        /// Close event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.DialogResult = true;
        }

        /// <summary>
        /// Default const
        /// </summary>
        /// <param name="ID"></param>
        public SettingDialog(int ID)
            : this()
        {
            this.busyind.IsBusy = true;
            Load(ID);
        }

        /// <summary>
        /// Load Setting shortcut Items
        /// </summary>
        /// <param name="ID"></param>
        private void Load(int ID)
        {
            bool isBaseLang = Envs.IsBaseLanguage(Envs.GetCtx(), "AD_Shortcut");


            string sql = @"SELECT o.Name AS Name,
                                  o.AD_Image_ID AS AD_Image_ID,
                                  o.Classname AS ClassName  ,
                                  o.Action  AS Action   ,
                                  (
                                  CASE
                                    WHEN o.action = 'W'
                                    THEN o.ad_window_id
                                    WHEN o.action='P'
                                    OR o.action  ='R'
                                    THEN o.ad_process_id
                                    WHEN o.action = 'B'
                                    THEN o.ad_workbench_id
                                    WHEN o.action = 'T'
                                    THEN o.ad_task_id
                                    WHEN o.action = 'X'
                                    THEN o.ad_form_id
                                    WHEN o.action ='F'
                                    THEN o.ad_workflow_id
                                    ELSE 0
                                  END ) AS ActionID, o.ad_shortcut_id as ID,  o.Url as Url, ";

            if (isBaseLang)
            {
                sql += " o.DisplayName as Name2 FROM AD_Shortcut o ";
            }
            else
            {
                sql += " trl.Name as Name2 FROM AD_Shortcut o INNER JOIN AD_Shortcut_Trl trl ON o.AD_Shortcut_ID = trl.AD_Shortcut_ID "
                         + " AND trl.AD_Language =  '" + Envs.GetAD_Language(Envs.GetCtx()) + "' ";
            }
            sql += @" WHERE o.AD_Client_ID = 0
                                  AND o.IsActive         ='Y'
                                  AND o.IsChild          = 'Y'
                                  AND o.Parent_ID =  " + ID + @"
                                 ORDER BY SeqNo";

            System.Data.DataSet ds = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    ds = DataBase.DB.ExecuteDataset(sql, null);
                }
                catch
                {
                    Dispatcher.BeginInvoke(delegate
                    {
                        this.busyind.IsBusy = false;
                    });
                    return;
                }
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        int AD_Image_ID = Utility.Util.GetValueOfInt(dr["AD_Image_ID"]);
                        if (AD_Image_ID > 0)
                        {
                            lstImgSource.Add(new Model.MImage(Envs.GetCtx(), AD_Image_ID, null).GetImage());
                        }
                        else
                        {
                            lstImgSource.Add(null);
                        }
                    }
                }

                Dispatcher.BeginInvoke(() => CreateShortCuts(ds));
            });




        }

        /// <summary>
        /// Create shortcut
        /// </summary>
        /// <param name="ds"></param>
        private void CreateShortCuts(System.Data.DataSet ds)
        {
            if (ds == null || ds.Tables[0].Rows.Count < 1)
            {
                this.busyind.IsBusy = false;
                return;
            }
            int i = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                DesktopShortcutItem itm = new DesktopShortcutItem();
                itm.Icon = lstImgSource[i];
                itm.ShortcutName = Util.GetValueOfString(dr["Name2"]);
                itm.Action = Util.GetValueOfString(dr["Action"]);
                itm.ActionID = Util.GetValueOfInt(dr["ActionID"]);
                itm.SpecialAction = Util.GetValueOfString(dr["ClassName"]);
                itm.ActionName = Util.GetValueOfString(dr["Name"]);
                itm.Url = (Util.GetValueOfString(dr["Url"]));
                itm.KeyID = Util.GetValueOfInt(dr["ID"]);
                //itm.DynamicActionID = Util.GetValueOfInt(dr["DynamicActionID"]);
                itm.Explorer = Envs.Desktop;
                itm.Margin = new Thickness(5, 15, 5, 4);
                itm.DoubleClick += new RoutedEventHandler(Item_DoubleClick);
                wpContainer.Children.Add(itm);

                i++;
            }
            this.busyind.IsBusy = false;
            lstImgSource.Clear();
            lstImgSource = null;
            Envs.SetBusyIndicator(false);
        }

        /// <summary>
        /// Start Entity Acions
        /// </summary>
        /// <param name="action">action char( 'W','x')</param>
        /// <param name="cmd">Key ID</param>
        internal void StartAction(string action, int cmd)
        {
            AMenuStartItem aStart = new AMenuStartItem(cmd, true, "", this);
            action = action.Trim();
            if (action.Equals("W"))				//	Window
            {
                aStart.StartWindow(0, cmd);
            }
            else if (action.Equals("P") || action.Equals("R"))	//	Process & Report
            {
                aStart.StartProcess(cmd);
            }
            else if (action.Equals("B"))		//	Workbench
            {
                aStart.StartWindow(cmd, 0);
            }
            else if (action.Equals("F"))		//	WorkFlow
            {
                //if (_isMenu)
                //    cmd = Utility.Util.GetValueOfInt(dr["AD_Workflow_ID"]);
                //else
                //    cmd = Utility.Util.GetValueOfInt(dr["Workflow_ID"]);
            }
            else if (action.Equals("T"))		//	Task
            {
                aStart.StartTask(cmd);
            }
            else if (action.Equals("X"))		//	Form
            {
                aStart.StartForm(cmd);
            }
            else
            {
                VLogger.Get().Log(Level.SEVERE, "No valid Action in ID=" + cmd);
            }
            aStart = null;
        }

        /// <summary>
        /// Double ClickEvent handler of Shortcut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Item_DoubleClick(object sender, RoutedEventArgs e)
        {
            Envs.SetBusyIndicator(true);
            DesktopShortcutItem dsi = sender as DesktopShortcutItem;

            //1   Contain Child ShortCut

            if (dsi.HasChild)
            {
                SettingDialog sd = new SettingDialog();
                sd.Show();
            }

            //2 If URL

            else if (!string.IsNullOrEmpty(dsi.Url))
            {
                Envs.StartBrowser(dsi.Url);
                Envs.SetBusyIndicator(false);
            }

            // 3 Special Class
            else if (!string.IsNullOrEmpty(dsi.SpecialAction))
            {
                string className = dsi.SpecialAction;

                //if (className.Equals("VAdvantage.Apps.RoleCenter", StringComparison.OrdinalIgnoreCase))
                //{
                //    IsAllowWorkSpace();
                //    return;
                //}

                //Get form Name
                String formName = dsi.ActionName;// className.Substring(className.LastIndexOf('.') + 1);

                try
                {
                    Assembly asm = null;
                    Type type = null;

                    /************  Module ****************/
                    try
                    {
                        //string formName = className.Substring(className.LastIndexOf('.') + 1);
                        Tuple<String, String> asmInfo = null;
                        if (Envs.HasModulePrefix(formName, out asmInfo))
                        {
                            asm = Assembly.Load(asmInfo.Item1);
                            type = asm.GetType(className);
                        }
                    }
                    catch (Exception ex)
                    {
                        VLogger.Get().Warning("Assembly => " + ex.Message);
                    }
                    /********************* END ******************/

                    if (type == null)
                    {
                        try
                        {
                            asm = Assembly.Load(VAdvantage.DataBase.GlobalVariable.PRODUCT_NAME);
                            type = asm.GetType(className);
                        }
                        catch
                        {
                            //asm = Assembly.Load(GlobalVariable.ASSEMBLY_NAME);
                        }
                    }

                    /*End Customization */

                    if (type == null)
                    {
                        type = Type.GetType(className);
                    }

                    if (type != null && type.IsClass)
                    {
                        try
                        {
                            object instance = Activator.CreateInstance(type);
                            if (instance is Form)
                            {
                                Form frm = (Form)instance;
                                Utility.Envs.RegisterWindowForm(frm);
                                frm.Show();
                            }
                            else if (instance is ChildWindow)
                            {
                                ((ChildWindow)instance).Show();
                            }
                        }

                        catch (Exception ex)
                        {
                            VAdvantage.Logging.VLogger.Get().Warning("No Instance for " + type.FullName + " (" + ex.ToString() + ")");
                        }
                    }
                    else
                    {
                        VLogger.Get().Info("Type not found against " + className);
                    }
                }
                catch (Exception exx)
                {
                    Envs.SetBusyIndicator(false);
                    VLogger.Get().Severe("Error " + className);
                    // return false;
                }
                Envs.SetBusyIndicator(false);
            }


            else //Entity Action
            {
                if (String.IsNullOrEmpty(dsi.Action) || dsi.ActionID < 1)
                {
                    VLogger.Get().Info("No action or action_ID against shortcut");
                    return;
                }
                StartAction(dsi.Action, dsi.ActionID);
            }
            this.DialogResult = true;
        }

        #region Ihost

        public void OnLoginCompleted()
        {
            //throw new NotImplementedException();
        }

        public void OnMenuLoad()
        {
            //throw new NotImplementedException();
        }

        public Explorer GetExplorer
        {
            get { return Envs.Desktop; }
        }

        public bool ShowBusyIndicator
        {
            get
            {
                return false;
            }
            set
            {
                //throw new NotImplementedException();
            }
        }

        public void StartMenuItemID(int id)
        {
            throw new NotImplementedException();
        }

        #endregion

        private void ScrollViewer_Loaded(object sender, RoutedEventArgs e)
        {
            Envs.SetBusyIndicator(false);
            //  Load(_id);
        }
    }
}





